//
//  aRcustomVC.m
//  DuoBaoKnigh
//
//  Created by aReu on 2016/11/4.
//  Copyright © 2016年 aReu. All rights reserved.

#import "aRcustomVC.h"
#import "aRNetworkRequest.h"
#import "aRModel.h"
#import "aRBanzouModel.h"
#import "PYSearch.h"
#import "AFNetworking.h"
#import "MJExtension.h"
#import "MJRefresh.h"
#import "aRCell.h"
#import "RegexKitLite.h"


@interface aRcustomVC ()<UITableViewDelegate,UITableViewDataSource>{
    BOOL _mp3Flag;
}

@property (nonatomic,strong)NSMutableArray * cellArr;
@property (strong , nonatomic) UITableView *reCordTableview;
@property (nonatomic,copy)  NSString *textStr;
@end

@implementation aRcustomVC
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"

- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) return nil;
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

- (NSArray *)componentsSeparatedFromString:(NSString *)fromString toString:(NSString *)toString  ByStr:(NSString*)tempString{
    if (!fromString || !toString || fromString.length == 0 || toString.length == 0)
        return nil;
    NSMutableArray *subStringsArray = [[NSMutableArray alloc] init];
    NSRange range = [tempString rangeOfString:fromString];
    while (range.location != NSNotFound) {
        tempString =[tempString substringFromIndex:(range.location + range.length)];
        range = [tempString rangeOfString:toString];
        if (range.location != NSNotFound) {
            NSString *str1 = [tempString substringToIndex:range.location];
            [subStringsArray addObject:str1];
            range = [tempString rangeOfString:fromString];
        }else{
            break;
        }
    }
    return subStringsArray;
}


-(UITableView*)reCordTableview{
    if (!_reCordTableview) {
        _reCordTableview            = [[UITableView alloc] initWithFrame:CGRectMake(0, aR_MaxY, aR_WIDTH, aR_HEIGHT - aR_MaxY)];
        _reCordTableview.delegate   = self;
        _reCordTableview.dataSource = self;
        _reCordTableview.rowHeight  = 100;
        
        [_reCordTableview registerNib:aRNibLoad(@"aRCell") forCellReuseIdentifier:@"aRCell"];
        _reCordTableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _reCordTableview.backgroundColor = aR_BGColor;
        MJWeakSelf
        _reCordTableview.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        }];
    }
    return _reCordTableview;
}

-(instancetype)initWithText:(NSString*)text{
    if ([text containsString:@"伴奏"]) {
        _mp3Flag = YES;
        text = [text stringByReplacingOccurrencesOfString:@"伴奏" withString:@""];
    }else _mp3Flag = NO;
    self.textStr = text;
    return [super init];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _cellArr = @[].mutableCopy;
    [self.view addSubview:self.reCordTableview];
    /*
     for (int i = 0; i<8; i++) {
     aRModel *mo = [aRModel new];
     mo.author = @"BIg Bang BIg Bang BIg Bang BIg";
     mo.title = @"IF YOU IF YOU IF YOU IF YOU";
     mo.pic = @"http://imgcache.qq.com/music/photo/album_500/82/500_albumpic_1023582_0.jpg";
     [self.cellArr addObject:mo];
     }
     */
    
    if (_mp3Flag) {
        [self getBanzouSetting:self.textStr];
    }else{
        [self requestDataByName:self.textStr];
    }

}

#pragma mark---Delegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return aRMutArr(self.cellArr.count);
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MJWeakSelf
    aRCell *cell = [tableView dequeueReusableCellWithIdentifier:@"aRCell" forIndexPath:indexPath];
    if (_mp3Flag) {//伴奏
        NSDictionary *mo  = self.cellArr[indexPath.row];
        //[cell.headimg sd_setImageWithURL:aRUrl(mo.pic) placeholderImage:nil options:0];
        cell.artist.text = mo[@"originSinger"];
        cell.songName.text = mo[@"originalName"];
        [cell setClickBack:^{
            [weakSelf getMP3Url:mo[@"songurl"]];
        }];
    }else{
        aRModel *mo  = self.cellArr[indexPath.row];
        [cell.headimg sd_setImageWithURL:aRUrl(mo.pic) placeholderImage:nil options:0];
        cell.artist.text = mo.author;
        cell.songName.text = mo.title;
        [cell setClickBack:^{
            [weakSelf copyMp3Url:mo.url];
        }];
    }
    return cell;
}



#pragma mark--------获取歌曲
-(void)copyMp3Url:(NSString*)str{
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = str;
    [UIView showloginTip:@"复制成功"];
}

-(void)getBanzouSetting:(NSString*)str{
    MJWeakSelf
    [self.cellArr removeAllObjects];
    NSString *reSr = [[@"http://search.5sing.kugou.com/?type=bz&keyword=" stringByAppendingString:str] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [self requestBanzou:reSr callBack:^(NSString *htmlStr) {
        if(!htmlStr){
            [UIView showloginTip:nil];
            return ;
        }
        NSArray *arr = [self componentsSeparatedFromString:@"var dataList =" toString:@"var totalCount" ByStr:htmlStr];
        NSArray *allDataArr = [self componentsSeparatedFromString:@"{" toString:@"}" ByStr:[arr firstObject]];
        for (NSString *str in allDataArr) {
            NSString *newStr = [NSString stringWithFormat:@"{%@}",str];
            NSString *regEx = @"<([^>]*)>";
            NSString * nnn = [newStr stringByReplacingOccurrencesOfRegex:regEx withString:@""];
            NSString *new1 = [nnn stringByReplacingOccurrencesOfString:@"\\" withString:@"aReu"];
            NSString *new2 = [new1 stringByReplacingOccurrencesOfString:@"aReuaReu" withString:@"\\"];
            NSString *newStr1 = [new2 stringByReplacingOccurrencesOfString:@"aReu" withString:@""];
            NSDictionary *dic = [self dictionaryWithJsonString:newStr1];
            if (dic) {
                [self.cellArr addObject:dic];
            }
        }
        [weakSelf.reCordTableview reloadData];
    }];
}

//伴奏url
-(void)getMP3Url:(NSString*)url{
    MJWeakSelf
    [self requestBanzou:url callBack:^(NSString *htmlStr) {
        NSArray *mp3Arr = [weakSelf componentsSeparatedFromString:@"<audio src=" toString:@"id=" ByStr:htmlStr];
        debugLog(@"%@",[mp3Arr firstObject]);
        if (![mp3Arr firstObject]) {
            [UIView showloginTip:@"nil"];
        }
        [weakSelf copyMp3Url:[mp3Arr firstObject]];
    }];
}





#pragma mark-------请求人声歌曲
-(void)requestDataByName:(NSString*)songName{
    MJWeakSelf
    _mp3Flag     = NO;
    aRNetworkRequest *re = [aRNetworkRequest shareInstance];
    NSString *reSr = [[@"http://5even.cc/music.php?do=mis&key=" stringByAppendingString:songName] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [re requestDataToEachPageSetting:^(id object, NSError *error) {
        if (!object) {
            [UIView showloginTip:@"无呢首歌"];
            return;
        }
        _cellArr = [aRModel mj_objectArrayWithKeyValuesArray:object];
        [weakSelf.reCordTableview reloadData];
    } byRequestUrlString:reSr];
}

#pragma mark--请求伴奏
-(void)requestBanzou:(NSString*)songName
            callBack:(void (^)(NSString *htmlStr))arCb
{
    AFHTTPSessionManager *manager =[AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:songName parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        NSString *result = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        arCb(result);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        debugLog(@"%@",error);
        arCb(nil);
    }];
}

























#pragma clang diagnostic pop
@end
